import React from 'react'
import {connect} from 'react-redux'
import { Form, message, Spin, Tabs, Affix, Button, Popconfirm, Tooltip, Icon } from "antd";
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
import baseService from "share/base.service";
import borrowService from "containers/loan-billing/borrow-and-return.service"
import {messages,queryCurrencyPrecision, deepFullCopy} from "share/common";
import ApproveHistory from 'components/template/approve-history';
import RelatedApplication from 'containers/request/new-request/related-application';
import Chooser from 'components/chooser';
import customField from "share/customField";
import travelUtil from "containers/request/travel-request/travelUtil";
import chooserDate from 'share/chooserData';
import config from "config";
import menuRoute from "routes/menuRoute";
import 'styles/loan-billing/my-borrow.scss'
import ExpenseCheckResult from 'containers/expense-report/components/expense-check-result'
import Condition from 'components/condition'
import moment from "moment";
const { If } = Condition;
const formItemLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 14, offset: 1},
};

let newBorrowThis = null;

class NewBorrow extends React.Component{
  constructor(props){
    super(props);
    newBorrowThis = this
    this.state = {
      loading: false,
      formInfo: {}, //表单信息
      info: {}, //编辑状态的初始值
      approvalHistory: [], //借款单历史
      defaultValues: [],
      referenceApplicationOID: '', //关联申请单
      formDefaultValue: [], //表单默认值
      signEnable: false,
      signCompanyOIDs: [],
      copyDefaultValues: [],
      isOnlyRow: true, //是否单行借款单
      submitLoading: false,
      saveLoading: false,
      myBorrow: menuRoute.getRouteItem('my-borrow'),
      loanDetail: menuRoute.getRouteItem('loan-detail'),
      deleteLoading: false,
      propsParams: {
        precision: queryCurrencyPrecision(props.company.baseCurrency)
      },
      requestDetailInfo: {}, //带过来的申请单详情
      showCheckResult: false,
      checkResult: [],
      jobId: '',
      jobInfo: {}
    }
  }

  componentWillMount() {
    if (this.props.params.applicantOID && this.props.params.applicantOID !== ':applicantOID') {
      baseService.changeLoginInfo(this.props.params.applicantOID).then(() => {
      }).catch(() => {
        message.error(messages('loan-billing.key60')/*呼，服务器出了点问题，请联系管理员或稍后再试:(*/);
      });
    }
  }

  componentDidMount() {
    this.getFormInfo();
    this.isCounterSignEnable();
    const { jobId } = this.props.params;
    if (jobId && jobId !== ':jobId') {
      this.setState({ jobId });
    }
  };

  //获取表单信息
  getFormInfo = () => {
    this.setState({loading: true});
    borrowService.getCustomForm(this.props.params.formOID).then(res => {
      this.resDataHandle(res.data.customFormFields);
      !this.props.params.loanBillOID && this.copyDefault(res,'create');
      this.setState({
        formInfo: res.data,
        loading: !!this.props.params.loanBillOID,
        isOnlyRow: res.data.formType === 2005
      },() => {
        const { applicationOID } = this.props.params;
        let requestOID = null;
        if(applicationOID && applicationOID !== ':applicationOID'){
          requestOID = applicationOID;
        }
        if (this.props.params.loanBillOID) {
          this.getInfo(requestOID)
        } else {
          this.getFormDefaultValue(requestOID)
        }
      });
    })
  };

  //表单信息处理
  resDataHandle = (fields) => {
    fields.map(item => {
      if (item.messageKey === 'applicant') {
        item.isReadOnly = true;
      }
    });
    fields.sort((a, b) => a.sequence > b.sequence || -1);
  };

  //编辑状态获取初值
  getInfo = (requestOID) => {
    const { loanBillOID } = this.props.params;
    Promise.all([
      borrowService.getDetailInfo(loanBillOID),
      requestOID && borrowService.getRequestDetail(requestOID)
    ]).then(res => {
      if (this.props.loginUser.userOID !== res[0].data.applicantOID) {
        baseService.changeLoginInfo(res[0].data.applicantOID);
      }
      this.setState({
        info: res[0].data,
        approvalHistory: res[0].data.approvalHistorys || [],
        defaultValues: res[0].data.customFormValues,
        referenceApplicationOID: res[0].data.referenceApplicationOID,
        propsParams: {
          precision: queryCurrencyPrecision(res[0].data.currencyCode)
        },
        requestDetailInfo: res[1] ? res[1].data : {},
        jobId: res[0].data.jobId
      },() => {
        const { jobId } = this.state;
        borrowService.getJobInfo(jobId).then(res => {
          this.setState({
            loading: false,
            jobInfo: res.data
          });
        })
      });
      this.copyDefault(res[0],'edit');
    }).catch(() => {
      message.error(messages('loan-billing.key25')/*系统异常*/);
    });
  };

  copyDefault = (res, status) => {
    let dev = [];
    dev.checkedChange = this.checkedChange;//设置监听
    //添加更改状态单子不可编辑 部门，成本中心，申请人，参与人
    if(res.data.sourceApplicationOID){
      res.data.customFormValues = travelUtil.setDisabledValues(res.data.customFormValues);
    }
    if(!this.props.params.loanBillOID && status === 'create'){
      res.data.customFormFields.map(m => {
        dev.push({
          value: m.value,
          messageKey: m.messageKey,
          fieldOID: m.fieldOID,
          fieldName:m.fieldName,
          required:m.required,
          formType: 2005,
          showName:{name:m.showValue},
          dataSource:m.dataSource
        });
      });
      this.setState({copyDefaultValues: dev});
    }else if(status === 'edit'){
      res.data.customFormValues.map(m => {
        dev.push({
          value: m.value,
          messageKey: m.messageKey,
          formValueOID: m.formValueOID,
          fieldOID: m.fieldOID,
          fieldName:m.fieldName,
          required:m.required,
          formType: 2005,
          showName:{name:m.showValue},
          initValue:{value:m.value,name:m.showValue},
          showValue:m.showValue,
          dataSource:m.dataSource
        });
      });
      this.setState({copyDefaultValues: dev});
    }
  };

  checkedChange = (field,value,allValue) => {
    const { enableDepCompany } = this.props, { setFieldsValue, resetFields, getFieldsValue } = this.props.form;
    let copy = this.state.copyDefaultValues;
    let isChangeCompany = false, isChangeCurrencyCode = false, isChangeDepartment = false;
    let { formInfo, defaultValues, propsParams, formDefaultValue } = this.state;
    let customForm = this.props.params.loanBillOID ? defaultValues || [] : formInfo.customFormFields || [];
    let id = this.props.params.loanBillOID ? 'formValueOID' : 'fieldOID';
    copy.map(res => {
      if (res.messageKey === field.messageKey && res.fieldOID === field.fieldOID) {
        let defaultVal = null
        formDefaultValue.some((item) => {
          if (item.fieldOID === field.fieldOID) {
            defaultVal = item.value;
            return true
          }
        });
        if ((field.messageKey === 'select_cost_center' || field.messageKey === 'select_department') && (value !== defaultVal)) {
          res.showName = allValue;
          field.messageKey === 'select_department' && (isChangeDepartment = true);
        }
        if (field.messageKey === 'select_company') {
          isChangeCompany = true;
        }
        if (field.messageKey === 'currency_code') {
          isChangeCurrencyCode = true;
          propsParams.precision = queryCurrencyPrecision(value);
        }
        res.value = value;
      }
    });
    //切换了公司要清空成本中心
    if(isChangeCompany){
      customForm.map(i => {
        if (i.messageKey === 'select_cost_center' && !i.isReadOnly) {
          this.setState({ loading: true });
          baseService.checkCostCenterNeedEmpty().then(res => {
            this.setState({ loading: false });
            if (res.data.visible) {
              setFieldsValue({[i.fieldOID]: undefined});
              copy.map(item => {
                if (item.messageKey === 'select_cost_center') {
                  item.showName = undefined;
                  item.value = '';
                }
              })
            }
          });
        }
        if (i.messageKey === 'select_department' && !i.isReadOnly && enableDepCompany === 'OPEN') {
          setFieldsValue({[i.fieldOID]: undefined});
          copy.map(item => {
            if (item.messageKey === 'select_department') {
              item.showName = undefined;
              item.value = '';
            }
          })
        }
      });
      // 清空收款单位
      const venMaster = customForm.filter(item => {
        return item.messageKey === 'venMaster'
      })[0];
      if (venMaster) {
        resetFields(venMaster.fieldOID);
      }
    }
    if (isChangeDepartment) {
      customForm.map(i => {
        if (i.messageKey === 'select_cost_center' && !i.isReadOnly) {
          this.setState({ loading: true });
          baseService.checkCostCenterNeedEmpty().then(res => {
            this.setState({ loading: false });
            if (res.data.visible) {
              setFieldsValue({[i.fieldOID]: undefined});
              copy.map(item => {
                if (item.messageKey === 'select_cost_center') {
                  item.showName = undefined;
                  item.value = '';
                }
              })
            }
          });
        }
      });
    }
    if(isChangeCurrencyCode){
      let setData = {};
      copy.map(item => {
        if (item.messageKey === 'total_budget') {
          let temp = Number(this.filterMoney(getFieldsValue()[item[id]],propsParams.precision,true).replace(/,/mg,''));
          item.value = temp;
          setData[item[id]] = temp;
        }
      });
      setFieldsValue(setData);
    }
    this.setState({copyDefaultValues:copy, propsParams});
  };

  //新建获取默认值
  getFormDefaultValue = (requestOID) => {
    let userOID = this.props.user.userOID;
    const { applicantOID, formOID, jobId } = this.props.params;
    if (applicantOID && applicantOID !== ':applicantOID') {
      userOID = applicantOID;
    }
    let temp = { userOID, formOID };
    jobId && jobId !== ':jobId' && (temp.jobId = jobId);
    Promise.all([
      borrowService.getFormValue(temp),
      requestOID && borrowService.getRequestDetail(requestOID)//拿申请单详情
    ]).then(res => {
      this.setState({
        formDefaultValue: res[0].data,
        requestDetailInfo: res[1] ? res[1].data : {}
      },() => {
        borrowService.getJobInfo(jobId).then(res => {
          this.setState({
            loading: false,
            jobInfo: res.data
          });
        })
      })
    }).catch(() => {
      message.error(messages('loan-billing.key25')/*系统异常*/);
      this.setState({loading: false});
    })
  };

  //获取加签人
  isCounterSignEnable = () => {
    let params = {
      companyOID: this.props.company.companyOID,
      formOID: this.props.params.formOID,
      counterSignType: 'enableAddSignForSubmitter',
    };
    borrowService.postAddSignEnableScope(params).then(res =>{
      if (res.data.enabled) {
        this.setState({
          signEnable: res.data.enabled,
          signCompanyOIDs: res.data.approvalAddSignScope.companyOIDs
        });
      }
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

  //获取控件规则
  getRules = (field) => {
    let maxLength = undefined;
    switch (field.messageKey) {
      case 'remark':
        maxLength = 200;
        break;
      case 'text_area':
        maxLength = 1000;
        break;
      case 'title':
      case 'input':
        maxLength = 250;
        break;
      default :
        maxLength = undefined;
        break;
    }
    let rules = [];
    if (field.messageKey === 'public.assembly') {
      if (field.isHidden) {
        if (field.isSwitchOn) {
          rules.push({
            required: field.required,
            message: messages('common.can.not.be.empty', {name: field.fieldName})
          });
          if (field.required) {
            rules.push({
              validator: (rule, value, callback) => {
                if ([null, '[]'].includes(value)) {
                  callback('请填写完整');
                } else {
                  callback();
                }
              }
            });
          }
        } else {
          rules.push({
            required: false,
            message: messages('common.can.not.be.empty', {name: field.fieldName})
          });
        }
      } else {
        rules.push({
          required: field.required,
          message: messages('common.can.not.be.empty', {name: field.fieldName})
        });
        if (field.required) {
          rules.push({
            validator: (rule, value, callback) => {
              if ([null, '[]'].includes(value)) {
                callback('请填写完整');
              } else {
                callback();
              }
            }
          });
        }
      }
    } else {
      rules.push({
        required: field.required,
        message: messages('common.can.not.be.empty', {name: field.fieldName})
      });
    }

    maxLength && rules.push({
      max: maxLength,
      message: messages('common.max.characters.length', {max: maxLength})
    });
    (field.messageKey === 'out_participant_name' || field.messageKey === 'external_participant_name') && rules.push({
      validator: (rule, value, callback) => {
        let emptyItem = '';
        value && value.map(item => {
          if (!item.name) {
            emptyItem = messages('loan-billing.key61')/*姓名*/;
            return
          }
          if (!item.certificateNo) {
            emptyItem = messages('loan-billing.key62')/*证件号*/;
          }
        });
        if (!emptyItem) {
          callback();
          return
        }
        callback(messages('common.can.not.be.empty', {name: emptyItem}))
      }
    });
    if (['public.assembly'].includes(field.messageKey)) { // 是公用列表
      rules = [];
      if (field.isHidden) { // 展示“是否显示联动开关”
        if (field.isSwitchOn) { // 联动开关为true
          if (field.required) { // 设置了这个表单项必填
            rules.push({
              required: true,
              message: messages('common.name.is.required', { name: field.fieldName })  // ${field.fieldName}必填)
            });
            rules.push({
              validator: (rule, value, callback) => {
                if ([null, '[]'].includes(value)) {
                  callback('请填写完整');
                } else {
                  callback();
                }
              }
            });
          } else { // 设置这个表单项不是必填
            rules.push({
              required: false
            });
          }
        } else { // 联动开关关闭，那么这个表单项就是不必填的
          rules.push({
            required: false
          });
        }
      } else { // 不展示联动开关
        rules.push({
          required: field.required,
          message: messages('common.name.is.required', { name: field.fieldName })  // ${field.fieldName}必填)
        });
        if (field.required) {
          rules.push({
            validator: (rule, value, callback) => {
              if ([null, '[]'].includes(value)) {
                callback('请填写完整');
              } else {
                callback();
              }
            }
          });
        }
      }
    }
    return rules;
  };

  //关联申请单控件调用
  relatedApplication = (isNew) => {
    const { formInfo, info } = this.state;
    const { applicationOID } = this.props.params;
    let isDisabled = false;
    if(applicationOID && applicationOID !== ':applicationOID'){
      isDisabled = true;
    }
    return (
      <RelatedApplication formOID={this.props.params.formOID}
                          formInfo={formInfo}
                          disabled={info.directCreate || isDisabled}
                          applicantOID={this.props.user.userOID}
                          applicationOID={this.props.params.loanBillOID}
                          info={isNew ? {} : info}
                          isEdit={!isNew}
                          changeHandle={(value) => {this.setState({referenceApplicationOID: value[0] && value[0].applicationOID ? value[0].applicationOID : ''})}}/>
    )
  };

  // 当“是否显示关联”组件的switch的状态发生变化时触发
  onSwitchChange = (field, checked) => {
    const { form } = this.props;
    const map = item => {
      if (item.fieldOID === field.fieldOID) {
        return {
          ...item,
          isSwitchOn
        }
      }
      return item
    }
    
    this.setState({
      defaultValues: {
        ...this.state.defaultValues,
        custFormValues: 
          (this.state.defaultValues.custFormValues||[]).map(map)
      },
      formInfo: {
        ...this.state.formInfo,
        customFormFields: 
          (this.state.formInfo.customFormFields||[]).map(map)
      }
    }, () =>{ 
      form.validateFields([field.fieldOID], { force: true });
    })
  }

  //根据表单信息渲染控件
  renderCustom = (field,index,isNew) => {
    const { formInfo, formDefaultValue, info, defaultValues, copyDefaultValues, propsParams,
      requestDetailInfo, jobId, jobInfo } = this.state;
    const { getFieldDecorator,getFieldsValue } = this.props.form;
    let label = field.fieldName;
    if (field.messageKey === 'number') {
      JSON.parse(field.fieldContent || '{}').unit && (label = `${field.fieldName}(${JSON.parse(field.fieldContent || '{}').unit})`);
    }
    let rules = this.getRules(field);
    let fieldDefaultValue = {};
    let formDetailValues = formInfo;
    if(isNew){
      formDefaultValue.map(item => {
        item.fieldOID === field.fieldOID && (fieldDefaultValue = item)
      });
      if(field.messageKey === 'title'){
        requestDetailInfo.custFormValues && requestDetailInfo.custFormValues.map(item => {
          item.messageKey === 'title' && (fieldDefaultValue.value = item.value);
        });
      }
    }else{
      formDetailValues.currencyCode = info.currencyCode;
      formDetailValues.applicantOID = info.applicant && info.applicant.userOID;
      formDetailValues.customFormFields = defaultValues;
    };
    let identifyId = isNew ? field.fieldOID : field.formValueOID;
    let formDet = isNew ? formInfo : formDetailValues;
    if (field.fieldTips && field.fieldTips.length > 0) {
      label = <span>{label}&nbsp;
        <Tooltip title={field.fieldTips}>
          <Icon type="question-circle-o" />
        </Tooltip>
      </span>
    }
    return (
      <div key={index}>
        {index === 0 && field.messageKey !== 'applicant' && Object.keys(requestDetailInfo).length === 0 && (
          this.relatedApplication(isNew)
        )}
        <FormItem {...formItemLayout} label={label || ' '} key={identifyId} colon={!!label}>
          {getFieldDecorator(identifyId, {
            rules,
            valuePropName: field.messageKey === 'switch' ? 'checked' : 'value',
            initialValue: isNew ? customField.getDefaultValue(field, fieldDefaultValue) : customField.getInitialValue(field)
          })(
            customField.renderForm({
              field,fieldDefaultValue,
              formDetail: formDet,
              copyValue: copyDefaultValues,
              propsParams,
              formValues: getFieldsValue(),
              jobId,
              jobInfo,
              type: 3,
              onSwitchChange: this.onSwitchChange
            })
          )}
        </FormItem>
        {index === 0 && field.messageKey === 'applicant' && Object.keys(requestDetailInfo).length === 0 && (
          this.relatedApplication(isNew)
        )}
      </div>
    )
  };

  //提交或下一步
  handleSubmit = () => {
    this.handleSave(this.state.isOnlyRow);
  };

  //保存
  handleSave = (flag = false) => {
    let isEdit = this.props.params.loanBillOID ? true : false;
    let customFormFields = isEdit ? this.state.info.customFormValues : this.state.formInfo.customFormFields;
    let isHaveValidate = false;
    let isContainer = false;
    let needValidateForms = ['venMasterSwitch', 'linkage_switch'];
    customFormFields && customFormFields.map(item => {
      if (~needValidateForms.indexOf(item.messageKey)) {
        let info = this.props.form.getFieldValue(!isEdit ? item.fieldOID : item.formValueOID);
        if (info) {
          info.callBackSubmit = !info.callBackSubmit;
          this.props.form.setFieldsValue({[!isEdit ? item.fieldOID : item.formValueOID]: info},() => {
            let isPassValid = true;
            let values = this.props.form.getFieldValue(!isEdit ? item.fieldOID : item.formValueOID);
            if (values) {
              isPassValid = !isPassValid || values.isPassValid;
            }
            isContainer = true;
            isHaveValidate = isPassValid;
          });
        }
      }
    });
    setTimeout(() => {
      if((isContainer && isHaveValidate) || (!isContainer)){
        let isSubmit = typeof flag === 'boolean';
        this.delayHandleSave(isSubmit ? flag : false,isSubmit ? 'submit' : 'save');
      }
    },10);
  };

  //处理保存
  delayHandleSave = (isSubmit,type) => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { info, formInfo, referenceApplicationOID, isOnlyRow, requestDetailInfo, jobId } = this.state;
        const { applicationOID } = this.props.params;
        let params = this.props.params.loanBillOID ? JSON.parse(JSON.stringify(info)) : JSON.parse(JSON.stringify(formInfo));
        params.customFormValues = this.getCustomFormValues(values);
        params.referenceApplicationOID = referenceApplicationOID;
        params.jobId = jobId;
        params.countersignApproverOIDs = this.props.form.getFieldsValue().addSign;
        if (!this.props.params.loanBillOID) {
          params.remark = '';
        }
        let applicantOIDs = null;
        let companyOIDs = null;
        let totalAmount = 0;
        params.customFormValues.map((item, index) => {
          if(item.messageKey === 'applicant'){
            applicantOIDs = item.value;
          }
          if(item.messageKey === 'select_company'){
            companyOIDs = item.value;
          }
          if(item.messageKey === 'total_budget'){
            totalAmount = item.value;
          }
        });
        if(requestDetailInfo.personalPaymentAmount && requestDetailInfo.personalPaymentAmount < totalAmount){
          message.error(messages('loan-billing.key95')/*借款单总金额超出范围，请重新输入！*/);
          return -1;
        }
        params.applicantOID = applicantOIDs ? applicantOIDs : (params.applicantOID ? params.applicantOID : this.props.user.userOID);
        if (this.props.params.ifProxy === '1') { // 代提借款单，applicantOID传路由中的applicantOID,增加isProxy=1
          params.applicantOID = this.props.params.applicantOID
          params.isProxy = 1
        }
        params.companyOID = companyOIDs ? companyOIDs : (params.companyOID ? params.companyOID : this.props.company.companyOID);
        params.type = formInfo.formType;
        if(applicationOID && applicationOID !== ':applicationOID'){
          params.referenceApplicationOID = applicationOID;
          params.directCreate = 1;
        }
        delete params.createdDate;
        delete params.customFormFields;
        delete params.customFormProperties;
        delete params.customFormPropertyMap;
        delete params.referenceApplication;
        if(isSubmit){
          this.setState({submitLoading: true});
          borrowService.handleSubmit(params).then(res => {
            this.setState({submitLoading: false});
            if(Array.isArray(res.data)){
              this.setState({
                checkResult: res.data,
                showCheckResult: true
              })
            } else {
              message.success(messages('common.operate.success'));
              this.goBack();
            }
          }).catch(e => {
            this.setState({submitLoading: false});
            message.error(e.response.data.message);
          })
        }else{
          isOnlyRow ? this.setState({saveLoading: true}) : (type === 'submit' ? this.setState({submitLoading: true}) : this.setState({saveLoading: true}));
          borrowService.handleSave(params).then(res => {
            if(isOnlyRow){
              this.setState({saveLoading: false});
              message.success(messages('common.save.success', {name: ''}));
              this.goBack();
            }else{
              message.success(messages('common.operate.success'));
              if(type === 'submit'){
                this.setState({submitLoading: false});
                if(applicationOID && applicationOID !== ':applicationOID'){
                  this.context.router.push(menuRoute.getRouteItem('loan-detail').url.replace(':formOID', res.data.formOID).replace(':loanBillOID', res.data.loanBillOID).replace(':applicationOID', applicationOID))
                } else {
                  this.context.router.push(this.state.loanDetail.url.replace(':formOID', res.data.formOID).replace(':loanBillOID', res.data.loanBillOID))
                }
              } else {
                this.setState({saveLoading: false});
                this.goBack();
              }
            }
          }).catch(e => {
            isOnlyRow ? this.setState({saveLoading: false}) : this.setState({submitLoading: false});
            let error = e.response.data;
            if (error.validationErrors && error.validationErrors.length) {
              message.error(`${error.validationErrors[0].message}`);
            } else {
              message.error(`${error.message}`);
            }
          })
        }
      }
    });
  };

  getCustomFormValues = (values) => {
    let customFormValues = this.props.params.loanBillOID ? JSON.parse(JSON.stringify(this.state.info.customFormValues)) : JSON.parse(JSON.stringify(this.state.formInfo.customFormFields));
    customFormValues.map(item=> {
      Object.keys(values).map(key => {
        if (key === item.fieldOID || key === item.formValueOID) {
          item = customField.formatFormValue(item, values[key]);
        }
      })
    });
    return customFormValues;
  };

  //返回
  goBack = () => {
    menuRoute.goBack(this)
    // const { requestDetailInfo } = this.state;
    // const { applicationOID } = this.props.params;
    // if(applicationOID && applicationOID !== ':applicationOID'){
    //   this.context.router.push(menuRoute.getRouteItem(requestDetailInfo.status === 1001 ? 'request-edit' : 'request-detail').url.replace(':formOID',requestDetailInfo.formOID).replace(':applicationOID',applicationOID));
    // } else {
    //   this.context.router.push(this.state.myBorrow.url);
    // }
  };

  //删除
  handleDelete = () => {
    const { info } = this.state;
    this.setState({deleteLoading: true});
    borrowService.deleteRequest(info.loanBillOID).then(() => {
      this.setState({deleteLoading: false});
      message.success(messages('common.delete.success', {name: ''}));
      this.goBack()
    }).catch(() => {
      this.setState({deleteLoading: false});
      message.error(messages('common.operate.filed'))
    })
  };

  onValuesChange = (values) => {
    let customFormValues = this.props.params.loanBillOID ? JSON.parse(JSON.stringify(this.state.info.customFormValues)) : JSON.parse(JSON.stringify(this.state.formInfo.customFormFields));
    let changeDateFieldOID = null
    let costCenterItemOID = null
    customFormValues.map(item => {
      if(item.messageKey === 'common.date'){
        changeDateFieldOID = item.fieldOID
      }
    })
    customFormValues.map(item => {
      Object.keys(values).map(key => {
        costCenterItemOID = values[key]
        if ((key === item.fieldOID && item.messageKey === 'select_cost_center') || (key === item.formValueOID && item.messageKey === 'select_cost_center')) {
          baseService.getCostCenterItemDetailOne(costCenterItemOID).then(res => {
            let data = res.data;
            let storeOpenDate = data.storeOpenDate
            if(null != storeOpenDate){
              this.props.form.setFieldsValue({[changeDateFieldOID]:moment(storeOpenDate.toString())});
            }else {
              this.props.form.setFieldsValue({[changeDateFieldOID]:undefined});
            }
          })
        }
      })
    })
  }

  render(){
    const { loading, approvalHistory, signEnable, defaultValues, formInfo, info, signCompanyOIDs, isOnlyRow,
      submitLoading, saveLoading, deleteLoading, showCheckResult, checkResult } = this.state;
    const { getFieldDecorator } = this.props.form;
    let signPerson = [];
    let signName = customField.getSignNameForSubmitter(formInfo && formInfo.customFormPropertyMap);
    info.countersignApproverNames && info.countersignApproverNames.map(item => {
      signPerson.push({userOID: item.userOID, fullName: item.fullName})
    });
    const customFormFields = formInfo.customFormFields || [];
    let chooserItem = chooserDate.user;
    if(signCompanyOIDs.length > 0){
      chooserItem.url = `${config.baseUrl}/api/users/v3/search?corporationOID=${signCompanyOIDs}`;
    }
    let requestInfo = (
      <div>
        <h3 className="header-title">{formInfo.formName}</h3>
        <Form className="form-container" onValuesChange={this.onValuesChange}>
          <div style={{margin: '0 0 20px 30%'}}>{customField.instructionsTag(formInfo.customFormPropertyMap)}</div>
          {this.props.params.loanBillOID ? (
            defaultValues.map((field, index) => {
              return this.renderCustom(field,index,false);
            })
          ) : (
            customFormFields.map((field, index) => {
              return this.renderCustom(field,index,true)
            })
          )}
          {/* {signEnable && (
            <FormItem {...formItemLayout} label={signName} key="addSign">
              {getFieldDecorator('addSign', {
                rules: [{
                  required: formInfo.customFormPropertyMap && formInfo.customFormPropertyMap.enableCounterSignForSubmitterMustWriter === 'true',
                  message: messages('common.can.not.be.empty', {name: signName})
                }],
                initialValue: signPerson
              })(
                <Chooser selectorItem={chooserItem}
                         valueKey="userOID"
                         labelKey="fullName"
                         onlyNeed="userOID"
                         listExtraParams={{roleType: 'TENANT'}}
                         showArrow={formInfo.customFormPropertyMap && formInfo.customFormPropertyMap.countersignType === '2'}
                         newline/>
              )}
            </FormItem>
          )} */}
        </Form>
      </div>
    );
    return(
      <div className='my-borrow'>
        <Spin spinning={loading}>
          { !! approvalHistory.length && (
            <Tabs type="card">
              <TabPane tab={messages('loan-billing.key64')/*申请单信息*/} key="requestInfo">{requestInfo}</TabPane>
              <TabPane tab={messages('loan-billing.key39')/*审批历史*/} key="approvals">
                <ApproveHistory approvalChains={info.approvalChains} isShowReply={false} businessCode={info.businessCode} approvalHistory={approvalHistory} applicantInfo={info.applicant || {}}/>
              </TabPane>
            </Tabs>
          )}
          { !approvalHistory.length && requestInfo }
        </Spin>
        <Affix offsetBottom={0} className="bottom-bar">
          <If value={!info.directCreate || this.props.params.applicationOID !== ':applicationOID'}>
            <div style={{display: 'inline-block'}}>
              <If value={this.props.params.applicationOID === ':applicationOID' || !isOnlyRow}>
                <Button type="primary" onClick={this.handleSubmit} loading={submitLoading}>{isOnlyRow ? messages('common.submit') : messages('loan-billing.key65')/*下一步*/}</Button>
              </If>
              <If value={info.status === 1001}>
                <Popconfirm title={messages('common.confirm.delete')} placement="topRight" onConfirm={this.handleDelete}>
                  <Button className="delete-btn" loading={deleteLoading}>{messages('common.delete')}</Button>
                </Popconfirm>
              </If>
              <Button onClick={this.handleSave} loading={saveLoading}>{messages('common.save')}</Button>
            </div>
          </If>
          <Button onClick={this.goBack}>{messages('common.back')}</Button>
        </Affix>
        <ExpenseCheckResult
          visible={showCheckResult}
          checkResult={checkResult}
          onCancel={() => {
            this.setState({showCheckResult: false})
          }}
        />
      </div>
    )
  }
}

NewBorrow.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state){
  return {
    company: state.login.company,
    user: state.login.user,
    loginUser: state.login.loginUser,
    enableDepCompany: state.setting.enableDepCompany
  }
}

const wrappedNewBorrow = Form.create(
  {
    onValuesChange(props, values) {
      newBorrowThis.onValuesChange(values);
    },
  }
)(NewBorrow);

export default connect(mapStateToProps)(wrappedNewBorrow);
